// 时间总线，发布订阅设备消息、上下线、事件、告警
package eventbus

import (
	"fmt"
	"go-iot/app/iot/eventbus/matcher"
	"go-iot/app/iot/eventbus/message"
)


var eventBus = newEventBus()

func newEventBus() *SingleNodeEventBus {
	return &SingleNodeEventBus{
		data:    map[string][]func(data message.Message){},
		matcher: *matcher.NewAntPathMatcher(),
	}
}


// /device/{productId}/{deviceId}/property
func GetMesssageTopic(productId string, deviceId string) string {
	return fmt.Sprintf("/device/%s/%s/property", productId, deviceId)
}

// /device/{productId}/{deviceId}/online
func GetOnlineTopic(productId string, deviceId string) string {
	return fmt.Sprintf("/device/%s/%s/online", productId, deviceId)
}

// /device/{productId}/{deviceId}/offline
func GetOfflineTopic(productId string, deviceId string) string {
	return fmt.Sprintf("/device/%s/%s/offline", productId, deviceId)
}

// /device/{productId}/{deviceId}/event
func GetEventTopic(productId string, deviceId string) string {
	return fmt.Sprintf("/device/%s/%s/event", productId, deviceId)
}

// /device/{productId}/{deviceId}/alarm
func GetAlarmTopic(productId string, deviceId string) string {
	return fmt.Sprintf("/device/%s/%s/alarm", productId, deviceId)
}

// /device/{productId}/{deviceId}/debug
func GetDebugTopic(productId string, deviceId string) string {
	return fmt.Sprintf("/device/%s/%s/%s", productId, deviceId, message.DEBUG)
}

func Subscribe(pattern string, run func(msg message.Message)) {
	eventBus.Subscribe(pattern, run)
}

func UnSubscribe(pattern string, run func(data message.Message)) {
	eventBus.UnSubscribe(pattern, run)
}

// publish event of alarm
func PublishAlarm(data *message.AlarmMessage) {
	eventBus.publish(GetAlarmTopic(data.ProductId, data.DeviceId), data)
}

// publish event of tsl properties
func PublishProperties(data *message.PropertiesMessage) {
	eventBus.publish(GetMesssageTopic(data.ProductId, data.DeviceId), data)
}

// publish event of tsl events
func PublishEvent(data *message.EventMessage) {
	eventBus.publish(GetEventTopic(data.ProductId, data.DeviceId), data)
}
func PublishOnline(data *message.OnlineMessage) {
	eventBus.publish(GetOnlineTopic(data.ProductId, data.DeviceId), data)
}
func PublishOffline(data *message.OfflineMessage) {
	eventBus.publish(GetOfflineTopic(data.ProductId, data.DeviceId), data)
}

func PublishDebug(data *message.DebugMessage) {
	eventBus.publish(GetDebugTopic(data.ProductId, data.DeviceId), data)
}
